<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <h1>POST</h1>
    <fieldset>
        <legend>Ajax表单提交</legend>
        <form>
            <input type="text" name="name"  onblur="doCheck()"/>
            <button type="button" onclick="doSave()">Save</button>
        </form>
        <span id="result"></span>
    </fieldset>
</div>
<script>
    function doSave() {
        //1,创建对象
        let xhr = new XMLHttpRequest();
        //2,设置监听
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("result").innerHTML = xhr.responseText;
            }
        }
        let name = document.forms[0].name.value;
        console.log("name", name);
        let url = 'http://localhost/doSave';
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
        //4,发送请求
        xhr.send('name=${name}');
    }
    function doCheck(){//发送异步请求,检查name是否存在
        //1.创建xhr对象(Ajax技术应用的入口)
        let xhr=new XMLHttpRequest();
        //2.设置状态监听(不是必须的,但是假如要获取服务端响应的结果并进行处理就要进行状态监听)
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200){
                document.getElementById("result").innerHTML=xhr.responseText;
            }
        }
        //3.建立Get连接(get请求传参数,要将参数拼接到url中)
        let name=document.forms[0].name.value;
        console.log("name",name);
        let url=`http://localhost/doCheck?name=${name}`;//通过模板字符串``和${}表示拼接url
        xhr.open("GET",url,true);
        //4.发送异步请求
        xhr.send(null);
    }
</script>
</body>
</html>